﻿package Core 
{
	import Albums.AlbumEvent;
	import Albums.AlbumIcon;
	import Albums.AlbumsPage;
	import com.junkbyte.console.Cc;
	import Common.CommonMessage;
	import Common.Room;
	import Events.ImageEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;	
	import flash.display.Bitmap;
	import flash.display.Sprite;	
	import flash.text.TextField;
	import flash.system.LoaderContext;
	import flash.system.SecurityDomain;	
	import flash.net.URLRequest;
	import flash.utils.ByteArray;		
	import flash.external.ExternalInterface;
	/**
	 * ...
	 * @author Serg de Adelantado
	 */
	public class ImagesUploader extends EventDispatcher 
	{	
		private var FContainer:ImagesViewer;
		private var FAlbums:AlbumsPage;
		private var FImagesProcessed:int;
		private var FUploaderURL:String;
		private var FUupdateURL:String;		
		private var FRoot:Main;
		private var FCurrentImages:Vector.<ImageContainer>;
		private var FCurrentAlbums:Vector.<AlbumIcon>;
		private var FMaxCount:int;
		private var FCurrent:int;
		private var FMessage:CommonMessage;
		private var FStartCategory:int;
		private var FCurrentRoom:int;
		private var FAlbumsProcessed:int;
		private var FAlbumToDelete:AlbumIcon;
		
		public function ImagesUploader() 
		{
			FAlbumsProcessed = 0;
			FImagesProcessed = 0;
			FStartCategory = 0;			
			FCurrentRoom = 0;
		}

		private function FinalURL(AName:String, ARotation:int = 0):String
		{
			var vResult:String = FUploaderURL;
			vResult += '?name=' + AName;
			if (ARotation != 0)
				vResult += '&rotation=' + ARotation;
			return vResult;
		}
		
		public function DeleteAlbum(AAlbum:AlbumIcon):void 
		{
			FAlbumToDelete = AAlbum;
			FCurrent = 0;
			FContainer.Category = AAlbum.ID;
			FCurrentImages = FContainer.ImagesByOwner(AAlbum.ID);
			FMessage = new CommonMessage();
			FRoot.MessagesCore.Show(FMessage);
			DeleteNextImage();
		}
		
		private function DeleteNextImage():void
		{
			if (FCurrent < FCurrentImages.length)
			{
				var vImage:ImageContainer = FCurrentImages[FCurrent];				
				vImage.CheckUpdates = false;
				vImage.Order = FCurrent + 1;
				vImage.CheckUpdates = true;
				FCurrent++;
				FMessage.Image = vImage.Photo.bitmapData;
				FMessage.Description = vImage.Description;				
				FMessage.Header = 'Удаление изображения ' + FCurrent + ' из ' + FCurrentImages.length;
				vImage.addEventListener(ImageEvent.UPDATE_COMPLETE, OnImageDeleted);
				vImage.addEventListener(ImageEvent.UPDATE_ERROR, OnImageDeleted);
				vImage.StartUpload();				
			}
			else
			{
				FAlbumToDelete.DoDelete();
			}
		}		
		
		private function OnImageDeleted(e:ImageEvent):void 
		{
			var vImage:ImageContainer = ImageContainer(e.target);					
			FContainer.RemoveImage(vImage);
			vImage.removeEventListener(ImageEvent.UPDATE_COMPLETE, OnImageUploaded);
			vImage.removeEventListener(ImageEvent.UPDATE_ERROR, OnImageUploaded);
			DeleteNextImage();	
		}
		
		public function Sync():void
		{
			//Stage 0 - Updating Albums
			FCurrentAlbums = FAlbums.Albums;
			FAlbumsProcessed = 0;
			FRoot.Blur();
			ProcessNextAlbum();			
		}		
		
		private function SyncImages():void
		{
			//Stage 1 - Updating Images
			FStartCategory = FContainer.Category;
			FMessage = new CommonMessage();
			FRoot.MessagesCore.Show(FMessage);
			FRoot.Blur();
			FContainer.AllButtonsEnabled = false;
			FCurrentRoom = 0;
			ProcessNextRoom();
		}
		
		private function ProcessNextAlbum():void
		{			
			if (FAlbumsProcessed < FCurrentAlbums.length)
			{
				FCurrentAlbums[FAlbumsProcessed].addEventListener(AlbumEvent.ALBUM_UPDATED, OnAlbumProcessed);
				FCurrentAlbums[FAlbumsProcessed].Update();
				FAlbumsProcessed++;				
			}
			else			
				SyncImages();
		}
		
		private function OnAlbumProcessed(e:AlbumEvent):void 
		{
			ProcessNextAlbum();
		}
		
		private function ProcessNextRoom():void
		{
			if (FCurrentRoom < FContainer.XMLS.Rooms.length)
			{
				var vRoom:Room = FContainer.XMLS.Rooms[FCurrentRoom];
				FContainer.Category = vRoom.ID;
				FCurrentImages = FContainer.CurrentImages;
				FCurrentRoom++;
				if (FCurrentImages.length > 0)
				{				
					FRoot.AlbumsTabs.CurrentAlbum = FContainer.Category;				
					FMaxCount = FCurrentImages.length;
					FMessage.MaximalPhotos = FMaxCount;
					FCurrent = 0;
					ProcessNextImage();
				}
				else				
					ProcessNextRoom();
			}
			else
			{
				FRoot.UnBlur();
				FContainer.Category = FStartCategory;
				FRoot.AlbumsTabs.CurrentAlbum = FContainer.Category;
				FRoot.MessagesCore.visible = false;
				FContainer.AllButtonsEnabled = true;				
			}
		}
		
		private function ProcessNextImage():void
		{
			if (FCurrent < FCurrentImages.length)
			{
				var vImage:ImageContainer = FCurrentImages[FCurrent];				
				vImage.CheckUpdates = false;
				vImage.Order = FCurrent + 1;
				vImage.CheckUpdates = true;
				FCurrent++;
				FMessage.CurrentImage = vImage;				
				FMessage.Description = vImage.Description;				
				FMessage.CurrentPhotoIndex = vImage.Order;
				vImage.addEventListener(ImageEvent.UPDATE_COMPLETE, OnImageUploaded);
				vImage.addEventListener(ImageEvent.UPDATE_ERROR, OnImageUploaded);
				vImage.StartUpload();				
			}
			else
				ProcessNextRoom();
		}
		
		private function OnImageUploaded(e:ImageEvent):void 
		{
			var vImage:ImageContainer = ImageContainer(e.target);
			if (vImage.MarkedForDelete)			
				FContainer.RemoveImage(vImage);			
			vImage.removeEventListener(ImageEvent.UPDATE_COMPLETE, OnImageUploaded);
			vImage.removeEventListener(ImageEvent.UPDATE_ERROR, OnImageUploaded);
			ProcessNextImage();			
		}
		
		//{ Getters & setters 
			
		public function get PageURL():String
		{
			var vResult:String = 'unknown';
			try
			{
				vResult = String(ExternalInterface.call(" function(){ return document.location.href.toString();}"));
			}
			catch (e:Error)
			{
				Cc.error(e.message)
			}
			if (vResult == null)
				vResult = 'unknown';
			return vResult;
		}
		
		public function set Container(AContainer:ImagesViewer):void
		{
			FContainer = AContainer;
			FRoot = FContainer.Root;
			FAlbums = FRoot.AlbumsTabs;
			FImagesProcessed = 0;
		}		
		//} endregion
		//End of getters & setters
	}
}